package org.igeek.atomqq.task;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.igeek.atomqq.activity.BaseActivity;
import org.igeek.atomqq.domain.Friend;
import org.igeek.atomqq.domain.FriendCategory;
import org.igeek.atomqq.net.HttpConnection;
import org.igeek.atomqq.net.HttpConnection.Request_TYPE;
import org.igeek.atomqq.net.Response;
import org.igeek.atomqq.util.URLManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


/**
 * 获取好友列表
 * 正常返回类型: application/json
 * 
 * POST application/json	https://s.web2.qq.com/api/get_user_friends2	
 * @author hangxin1940@gmail.com
 * @version 创建时间：2012-1-29 下午1:32:26
 * 
 */
public class FriendListTask extends CachedAsyncTask<Void,Void,Void>{
	public static final int ERROR=0x5025;
	
	private TaskResultListener listener;
	private FriendListResponse response;
	private int flag;
	
	private Handler handler=new Handler(){
		
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ERROR:
				activity.showDialog(ERROR, msg.getData());
				
				break;
			default:
				activity.showDialog(BaseActivity.DIALOG_ERROR, msg.getData());
				break;
			}
		}
	};
	
	private BaseActivity activity;
	
	public FriendListTask(BaseActivity activity){
		this.activity=activity;
	}
	
	public void setOnTaskResult(TaskResultListener listener,int flag){
		this.listener=listener;
		this.flag=flag;
	}
	

	@Override
	protected Void doInBackground(Void... params) {
		
		
		try {
			String vfwebqq=HttpConnection.getCookieManager().getCookieValue("vfwebqq");
			StringBuffer surl=new StringBuffer(URLManager.FRENDS_LIST);
			JSONObject post=new JSONObject();
			post.put("h", "hello");
			post.put("vfwebqq", vfwebqq);
			
			surl.append("?r=");
			surl.append(URLEncoder.encode(post.toString(),"utf-8"));
			
			
			
			
			URL url = new URL(surl.toString());
			
			HttpConnection conn=new HttpConnection(url, Request_TYPE.POST);
			conn.setReferer(URLManager.REFER_d_web2_qq_com_proxy);
			conn.connect();
			Response cesponses=conn.getResponse();
			conn.disconnect();
			
			JSONObject r=cesponses.getJsonObj();
			JSONObject result=r.getJSONObject("result");
			
			JSONArray cats=result.getJSONArray("categories");
			List<FriendCategory> cateogres=createCategory(cats);
			
			Map<Long,Friend> friends=createFriend(result);
			
			friends2categories(friends,cateogres);
			
			response=new FriendListResponse();
			response.setCateogres(cateogres);
			response.setFriends(friends);
			
			
			
		}catch (Exception e) {
			e.printStackTrace();
			showErrorDialog("网络异常",ERROR);
		}
		
		
		return null;
	}
	
	/**
	 * 将好友列表加之好友分组
	 * @param friends
	 * @param cateogres
	 */
	private void friends2categories(Map<Long,Friend> friends,List<FriendCategory> cateogres){
		for(Entry<Long, Friend> frds: friends.entrySet()){
			Friend f=frds.getValue();
			
			for(FriendCategory fc:cateogres){
				if(f.getCategory()==fc.getIndex()){
					fc.addFriend(f);
					break;
				}
			}
		}
		
	}

	/**
	 * 组装好友列表
	 * @param cats
	 * @return
	 * @throws JSONException
	 */
	private List<FriendCategory> createCategory(JSONArray cats) throws JSONException{
		
		List<FriendCategory> cateogres=Collections.synchronizedList(new ArrayList<FriendCategory>());
		
		
		boolean has0=false;
		for(int i=0;i<cats.length();i++){
			FriendCategory c=new FriendCategory();
			
			JSONObject cate = cats.getJSONObject(i);
			c.setIndex(cate.getInt("index"));
			c.setName(cate.getString("name"));
		
			if(c.getIndex()==0)
				has0=true;
			
			cateogres.add(c);				
			
		}
		
		if(!has0){
			FriendCategory c=new FriendCategory();
			c.setIndex(0);
			c.setName("我的好友");
			cateogres.add(0, c);
		}
		
		return cateogres;
		
	}
	
	/**
	 * 组装好友列表
	 * @param frs
	 * @return
	 * @throws JSONException 
	 */
	private Map<Long,Friend> createFriend(JSONObject frs) throws JSONException{
		Map<Long,Friend> friends=Collections.synchronizedMap(new HashMap<Long, Friend>());
		
		
		JSONArray frds=frs.getJSONArray("friends");
		if(frs.length() > 0	&& frds.getJSONObject(0).getLong("uin") == -2)
			throw new JSONException("好友列表获取错误");
		
		//好友信息
		for (int i = 0; i < frds.length(); i++) {
			JSONObject jfriend = frds.getJSONObject(i);	
			long uin=jfriend.getLong("uin");
			long flag=jfriend.getLong("flag");
			int catgory=jfriend.getInt("categories");
			
			
			Friend friend=new Friend(uin);
			friend.setFlag(flag);
			friend.setCategory(catgory);
			friends.put(uin, friend);
			
		}
		
		
		//好友备注名称
		JSONArray mkns=frs.getJSONArray("marknames");
		for (int i = 0; i < mkns.length(); i++) {
			JSONObject jmark = mkns.getJSONObject(i);
			long uin=jmark.getLong("uin");
			String markn=jmark.getString("markname");
			
			Friend friend=friends.get(uin);
			
			if(null!=friend)
				friend.setMarkname(markn);
		}
		
		
		
		//好友会员信息
		JSONArray vips=frs.getJSONArray("vipinfo");
		for (int i = 0; i < vips.length(); i++) {
			JSONObject vip = vips.getJSONObject(i);
			long uin=vip.getLong("u");
			int level=vip.getInt("vip_level");
			int is=vip.getInt("is_vip");
			
			Friend friend=friends.get(uin);
			
			if(null!=friend){
				friend.setVip(is);
				friend.setVip_level(level);
			}
		}
		
		
		JSONArray infos=frs.getJSONArray("info");
		for (int i = 0; i < infos.length(); i++) {
			JSONObject jinfo = infos.getJSONObject(i);
			long uin=jinfo.getLong("uin");
			int flag=jinfo.getInt("flag");
			String nick=jinfo.getString("nick");
			
			Friend friend=friends.get(uin);
			
			if(null!=friend){
				friend.setFace("");
				friend.setFlag(flag);
				friend.setNick(nick);
			}
			
		}
		
		return friends;
	}
	
	private void showErrorDialog(String message,int flag){
		Bundle bundle=new Bundle();
		bundle.putString(BaseActivity.FLAG_ERROR, message);
		Message msg=new Message();
		msg.setData(bundle);
		msg.what=flag;
		handler.sendMessage(msg );
	}
	
	@Override
	protected void onPostExecute(Void result) {
		listener.onTaskResult(response,flag);
	}	

	
	public class FriendListResponse extends Response{
		private Map<Long,Friend> friends;
		private List<FriendCategory> cateogres;

		public void setFriends(Map<Long,Friend> friends) {
			this.friends = friends;
		}

		public Map<Long,Friend> getFriends() {
			return friends;
		}

		public void setCateogres(List<FriendCategory> cateogres) {
			this.cateogres = cateogres;
		}

		public List<FriendCategory> getCateogres() {
			return cateogres;
		}
		
		
	}
}
